//
//  RoadsideAssistanceShopDetailViewController.m
//  JxCarios
//
//  Created by xcq on 15/2/1.
//  Copyright (c) 2015年 xiongchuanqi. All rights reserved.
//

#import "RoadsideAssistanceShopDetailViewController.h"
#import "RoadsideAssistanceMerchandiseCell.h"
#import "ReplaceDriveDetailCallCell.h"
#import "RoadsideAssistanceDayCell.h"
#import "RoadsideAssistanceShopDetailTableViewCell.h"
#import "LoginViewController.h"
#import "MyOrderViewController.h"
#import "ReplaceDriveDetailCallCell.h"
#define SHOPKEY @"goods"
#define SHOPTIME @"time"

static NSString *celldetailcall = @"detailcall";
static NSString *cellMerchandise = @"RoadsideAssistanceMerchandiseCell";
static NSString *cellShop = @"RoadsideAssistanceShopDetailTableViewCell";

@interface RoadsideAssistanceShopDetailViewController () <UIAlertViewDelegate,RoadSideCheckAction>
@property (nonatomic , retain)RoadsideAssistanceMerchandiseCell *_cell;
@property (nonatomic , retain)UIAlertView *alert;
@end

@implementation RoadsideAssistanceShopDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
      
    [self initAbout];
    self.tableView.hidden = YES;
    [self netRequest];
}

- (void)initAbout{
    self.title = @"路救";
    self.automaticallyAdjustsScrollViewInsets = NO;
    NSLog(@"%@",NSStringFromCGRect([RextExtends getScreenFrame]));
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, [RextExtends getScreenFrame].size.width, [RextExtends getScreenFrame].size.height) style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    [self.view sendSubviewToBack:self.tableView];
    [self showNavBarWithRightTitle:nil andRightAction:nil andLeftAction:nil andCustom:NO];
    REGISTCELL(@"RoadsideAssistanceMerchandiseCell", cellMerchandise);
    REGISTCELL(@"RoadsideAssistanceShopDetailTableViewCell", cellShop);
    REGISTCELL(@"ReplaceDriveDetailCallCell", celldetailcall);
}



- (BOOL)netRequest{
    if (self.carDataSource == nil) {
        self.carDataSource = [CarAroundDataSource dataSourceWithRequestor:self];
    }
    if (!_shopId) {
        return NO;
    }
    self.carDataSource.shopId = _shopId;
    [self.carDataSource getRoadsideAssistance:^(id result) {
        NSLog(@"%@",[result customObjectForkey:@"service_day"]);
        _shopDetailDic = [(NSDictionary *)result objectForKey:@"seller"];
        _daytimeDic = [(NSDictionary *)result objectForKey:@"service_day"];
        _nightDic = [(NSDictionary *)result objectForKey:@"service_night"];
        [self initWithDataSource];
    } anfFail:^(id result) {
        
    }];
    return YES;
}

- (void)initWithDataSource {
    _callDataSource = [NSMutableArray arrayWithArray:[[_shopDetailDic objectForKey:@"TEL"] componentsSeparatedByString:@","]] ;
    int i = 0 ;
    BOOL replace = NO;
    for (int a = 0 ;a < _callDataSource.count; a ++) {
        NSString *str = [_callDataSource objectAtIndex:a];
        if ([str isEqualToString:@"null"]) {
            i = a;
            replace = YES;
        }
    }
    if (replace) {
        [_callDataSource removeObjectAtIndex:i];
    }
    self.tableView.hidden = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


#pragma mark - tableView Delegate & dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return _callDataSource.count <= 0 ? 0 : _callDataSource.count;
            break;
        case 2:
            return 1;
            break;
        default:
            return 0;
            break;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {      //商家详细介绍
        RoadsideAssistanceShopDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellShop forIndexPath:indexPath];
        [cell.praiseView removeGestureRecognizer:cell.tap];
        [cell.negativeFeedbackView removeGestureRecognizer:cell.tap_two];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.info = _shopDetailDic;
        return cell;
    }else if (indexPath.section == 1){ //联系电话
        ReplaceDriveDetailCallCell *call = [tableView dequeueReusableCellWithIdentifier:celldetailcall forIndexPath:indexPath];
        call.selectionStyle = UITableViewCellSelectionStyleNone;
        
        call.phone.text = [_callDataSource objectAtIndex:indexPath.row];
        call.count = indexPath.row;
        return call;
    }else{                             //商品介绍
        __cell = [tableView dequeueReusableCellWithIdentifier:cellMerchandise forIndexPath:indexPath];
        __cell.selectionStyle = UITableViewCellSelectionStyleNone;
        __cell.delegate = self;
        __cell.firstDic = _daytimeDic;
        __cell.secondDic = _nightDic;
        if (![Common isBaiDay]) {
            [__cell firstBlock];
        }
        return __cell;
    }
}

 
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 0) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, _detailSize.height + 40)];
        view.backgroundColor = [UIColor whiteColor];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(2, 2, [RextExtends getScreenFrame].size.width, _detailSize.height)];
        label.backgroundColor = [UIColor redColor];
        if (_shopDetailDic) {
            label.text = [@"      " stringByAppendingString:[_shopDetailDic customObjectForkey:@"INTRODUCE"]] ;
        }
        label.font = [UIFont systemFontOfSize:13.0f];
        //清空背景颜色
        label.backgroundColor = [UIColor clearColor];
        //设置字体颜色为白色
        label.textColor = [UIColor blackColor];
        label.textAlignment = NSTextAlignmentLeft;
        //自动折行设置
        label.lineBreakMode = UILineBreakModeWordWrap;
        label.numberOfLines = 0;
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, label.frame.origin.y + _detailSize.height, [RextExtends getScreenFrame].size.width, 1)];
        lineView.backgroundColor = UICOLOR_MAKE_RGB(239, 238, 244);
        UILabel *addressLabel = nil;
        CGSize size = [Common sizeWithContent:[_shopDetailDic customObjectForkey:@"SHOP_ADDR"] AndFont:[UIFont systemFontOfSize:13.0f] andSize:CGSizeMake(([RextExtends getScreenFrame].size.width * 0.8 ) - 10 , 40) andLineBreak:UILineBreakModeWordWrap];
        if(size.height > (40 / 2) ){
            addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, lineView.frame.origin.y + 1 + 2, size.width, size.height + 5)];
        }else{
            addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, lineView.frame.origin.y + 1 + 10, size.width, size.height + 5)];
        }
        addressLabel.lineBreakMode = UILineBreakModeWordWrap;
        addressLabel.numberOfLines = 0;
        CGFloat distanceW = [RextExtends getScreenFrame].size.width ;
        UILabel *distanceLabel = [[UILabel alloc] initWithFrame:CGRectMake((distanceW * 0.8) + 20, lineView.frame.origin.y + 1 + 10, distanceW - 15, 20)];
        
        distanceLabel.font = [UIFont systemFontOfSize:11.0f];
        distanceLabel.text = [[NSString stringWithFormat:@"%.1f",[_distance doubleValue] / 1000] stringByAppendingString:@"Km"];
        distanceLabel.textColor = [UIColor grayColor];
        
        UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(distanceW * 0.8, distanceLabel.frame.origin.y + 2, 15, 15)];
        [imageV setImage:[UIImage imageNamed:@"dingwei"]];
        
        addressLabel.text = [_shopDetailDic customObjectForkey:@"SHOP_ADDR"];
        addressLabel.textAlignment = NSTextAlignmentLeft;
        addressLabel.font = [UIFont systemFontOfSize:13.0f];
        [view addSubview:distanceLabel];
        [view addSubview:imageV];
        [view addSubview:addressLabel];
        [view addSubview:lineView];
        [view addSubview:label];
        return view;
    }else{
        return nil;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else if(section == 1){
        return 20;
    }else{
        return 10;
    }
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 88;
    }else if (indexPath.section == 1){
        return 44;
    }else{
        
        return __cell.height;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        _detailSize = [Common sizeWithContent:[_shopDetailDic customObjectForkey:@"INTRODUCE"] AndFont:[UIFont systemFontOfSize:13.0f] andSize:[RextExtends getScreenFrame].size andLineBreak:UILineBreakModeWordWrap];
        _detailSize.height += 15;
        return _detailSize.height + 40;
    }
    return 10;
}

//点击回调
- (void)checkRoadSideCallBack:(UITableViewCell *)cell andSeleted:(BOOL)seleted{
    if (!_seletedShop) {
        _seletedShop = [NSMutableArray new];
    }
    RoadsideAssistanceDayCell *_cell = (RoadsideAssistanceDayCell *)cell;
    if (seleted) {
        [_seletedShop addObject:_cell.info];
        [self priceSum:YES price:[_cell.info customObjectForkey:@"CHEAP_PRICE"]];
        _settleAccountsView.hidden = NO;
    }else{
        [_seletedShop removeObject:_cell.info];
        [self priceSum:NO price:[_cell.info customObjectForkey:@"CHEAP_PRICE"]];

        if (_seletedShop.count == 0) {
            
            _settleAccountsView.hidden = YES;
        }
    }
}

- (void)priceSum:(BOOL)bol price:(NSString *)price{
    if (bol) { //+
        _checkPrice += [price doubleValue];
    }else{ //--
        _checkPrice -= [price doubleValue];
    }
    _settleAccountlLabel.text = [RMB stringByAppendingString:[NSString stringWithFormat:@"%.2f",_checkPrice]];
}


//总价格界面的checkBtn
- (IBAction)settleAccountCheck:(id)sender {
}

//确认按钮
- (IBAction)submitAction:(id)sender {
    
    if(![Common currenLoginStatus]){
        LoginViewController *login = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"LoginView"];
        CLUIBaseNavigationController *base = [[CLUIBaseNavigationController alloc] initWithRootViewController:login];
        login.hidesBottomBarWhenPushed = YES;
        [self presentViewController:base animated:YES completion:^{
            
        }];
    }else {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TipsGoOrder:) name:@"payTips" object:nil];

        PayViewController *pay = [[PayViewController alloc] initWithNibName:@"PayViewController" bundle:nil];
        pay.buyShopArr = [_seletedShop copy];
        pay.countPrice = _checkPrice;
        [self.navigationController pushViewController:pay animated:YES];
    }
}

- (void)TipsGoOrder:(NSNotification *)notification {
    _alert = [[UIAlertView alloc] initWithTitle:@"订单成功" message:@"您已经完成了订单!\n可前往我的订单中查看订单最新状态" delegate:self cancelButtonTitle:@"去看看" otherButtonTitles:@"下次再看", nil];
    _alert.tag = 500;
    [_alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if(buttonIndex == 0){
        MyOrderViewController *myorder = (MyOrderViewController *)[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"myOrder"];
        [self.navigationController pushViewController:myorder animated:YES];
        [_alert removeFromSuperview];

    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

@end
